import { Component, Injectable, OnInit, Input } from '@angular/core';
import { ControlApiService } from '@core/controlApi.service';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../../environments/environment';
declare const echarts: any;

@Injectable({ providedIn: 'root' })

@Component({
    selector: 'app-electricalnml',
    templateUrl: './electricalnml.component.html',
    styles: [`
        .nodata{height:290px;line-height:290px;text-align:center;color:#666}
        .w100{width:100%;height:300px}
        .w250{width:250px}   
        .kglTable{background:#f2f5fd;padding:0 5px 0 0;position:absolute;top:32px;left:0;overflow-y:auto}     
    `]
})

export class ElectricalnmlComponent implements OnInit {
    @Input() theme: any;
    @Input() dataType: any;
    @Input() styleHeight: any;
    @Input() queryParams: any;
    @Input() stationId: any;
    @Input() devNameText: any;
    @Input() scValue: any;
    @Input() sjValue: any;

    selectClass = 'defaultSelect';
    nodataText = '暂无电气特性数据';
    nodata = false;
    yzkdType = '';
    mnlTypeSelect: any = [];
    mnlTypeValue: any = [];
    popClass = '';
    viewType = '';
    eleVisible = false;
    viewEcharsList: any = [];
    viewEcharsData: any = [];
    kglTableList: any = [];
    viewEcharsName = '';
    viewEcharsValue1 = '';
    viewEcharsValue2 = '';
    viewEcharsValue11 = '';
    viewEcharsValue12 = '';
    viewEcharsValue13 = '';
    viewEcharsValue14 = '';

    viewStatus1 = false;
    viewStatus2 = false;
    viewStatus11 = false;
    viewStatus12 = false;
    viewStatus13 = false;
    viewStatus14 = false;

    kglTableStatus1 = false;
    kglTableStatus2 = false;
    kglTableStatus11 = false;
    kglTableStatus12 = false;
    kglTableStatus13 = false;
    kglTableStatus14 = false;

    constructor(
        private controlApiService: ControlApiService,
        private http: _HttpClient,
        private datePipe: DatePipe,
        public msg: NzMessageService
    ) { }

    ngOnInit() {
        if (this.theme) {
            switch (this.theme) {
                case 'blacktheme':
                    this.popClass = 'processWrap';
                    break;
                case 'whitetheme':
                    this.popClass = '';
                    break;
            }
        }
        // 转成监测设备类型和名称
        if (this.dataType === 'jc') {
            this.controlApiService.getDevname(this.stationId, this.queryParams.DEVTYPEID, '', '', this.queryParams.DEVNAME, '1', (devname: any) => {
                if (devname != '[]') {
                    devname = JSON.parse(devname);
                    this.queryParams.DEVNAMEID = devname[0].B_DEVTYPEID;
                    this.queryParams.DEVTYPE = devname[0].B_DEVTYPENAME;
                    this.queryParams.DEVNAMEID = devname[0].B_DEVID;
                    this.queryParams.DEVNAME = devname[0].B_DEVNAME;
                    this.devNameText = devname[0].B_DEVNAME;
                    this.qxtCharts();
                } else {
                    this.msg.error('未找到该监测设备关联的调度中心系统设备，请检查是否成功配置！', { nzDuration: 2000 });
                }
            });
        } else {
            this.qxtCharts();
        }
    }
    // 电气特性
    qxtCharts() {
        this.scValue = JSON.stringify(this.scValue).replace(/\"/g, '');
        if (!this.scValue || this.scValue === '') {
            this.scValue = '30';
        }
        // 画图
        if ((!this.queryParams.NID || this.queryParams.NID === 'undefined') && this.dataType === 'jc') {
            this.getdevnmlType(this.stationId, this.devNameText, () => {
                const data = this.mnlTypeSelect;
                let pro = '';
                let type = '';

                if (!this.mnlTypeSelect.length) {
                    this.nodata = true;
                    this.nodataText = '缺少模拟量数据';
                    return;
                }
                if (data.length) {
                    this.mnlTypeValue = data[0].ID;
                    for (const item of data) {
                        pro += ',' + item.PRO;
                    }

                    pro = pro.replace(',', '');
                    type = data[0].TYPE;

                    this.getmnlCharts(this.stationId, this.devNameText, this.sjValue, this.scValue, pro, type).subscribe((res: any) => {
                        const resdata = res.response.data;
                        if (!resdata.length) {
                            this.nodata = true;
                        } else {
                            this.getSelectData(resdata, 'name');
                        }
                    });
                }
            });
        } else {
            this.alarmMnl(this.sjValue, this.scValue, this.queryParams.NID).subscribe((res: any) => {
                const resdata = res.response.data;
                if (!resdata.length) {
                    this.nodata = true;
                } else {
                    this.getSelectData(resdata, 'dev_name');
                }
            });
        }
    }

    // 电气特性曲线
    alarmMnl(stime, duration, n_id) {
        const url = environment.apiBase + '/csmis/mnl/alarmMnl.jwt';
        // stime = '2019-03-27 20:10:25';
        const params = JSON.stringify({ 'stime': stime, 'duration': duration, 'n_id': n_id });
        return this.http.post(url, JSON.parse(params));
    }
    // 电气特性
    getmnlCharts(id, name, stime, duration, pro, type) {
        const url = environment.apiBase + '/csmis/mnl/dev.jwt';
        // let params = JSON.stringify({ "statId": "KMBUR_KMNSEG_STA_23", "devName": "7DG", "stime": "2019-03-28 02:29:11", "dev_pro": pro, "dev_type": type, "duration": "5" });
        const params = JSON.stringify({ 'statId': id, 'devName': name, 'stime': stime, 'duration': duration, 'dev_pro': pro, 'dev_type': type });
        return this.http.post(url, JSON.parse(params));
    }
    // 模拟量类型
    getdevnmlType(id, name, callback) {
        this.mnlTypeSelect = [];
        this.mnlTypeValue = [];
        this.getMnlType(id, name).subscribe((res: any) => {
            const data = res.response.data;
            if (data.length) {
                this.mnlTypeValue = data[0].ID;
                for (const item of data) {
                    if (item.DEV_PRO) {
                        this.mnlTypeSelect.push({ 'PRO': item.DEV_PRO, 'ID': item.ID, 'TYPE': item.DEV_TYPE });
                    }
                }
            } else {
                this.nodata = true;
                this.nodataText = '缺少模拟量数据';
                return;
            }
            callback();
        });
    }

    // 设备模拟量类型
    getMnlType(id, name) {
        const url = environment.apiBase + '/csmis/mnl/pro.jwt';
        const params = JSON.stringify({ 'statId': id, 'devName': name });
        // let params = JSON.stringify({ "statId": "KMBUR_KMNSEG_STA_16", "devName": "道岔" });
        return this.http.post(url, JSON.parse(params));
    }
    openModal() {
        this.eleVisible = true;
        this.getViewFullscreen(this.viewEcharsData, this.viewEcharsName);
    }
    fullOk() {
        this.eleVisible = false;
    }
    getSelectData(data, name) {
        this.viewEcharsData = data;
        this.viewEcharsName = name;
        this.viewEcharsList = [];

        for (let i = 0; i < data.length; i++) {
            let DEV_PRO = '';
            let DEV_TYPE = '';

            DEV_PRO = data[i].DEV_PRO;
            DEV_TYPE = data[i].DEV_TYPE;

            if (!DEV_PRO) {
                DEV_PRO = '';
            }
            if (!DEV_TYPE) {
                DEV_TYPE = '';
            }
            switch (name) {
                case 'name':
                    if (data[i].ALLKGL && data[i].ALLKGL.length) {
                        this.viewEcharsList.push({
                            id: i,
                            text: data[i].ALLKGL[0].DEV_PRO
                        });
                    } else {
                        this.viewEcharsList.push({
                            id: i,
                            text: data[i].NAME + DEV_PRO + DEV_TYPE
                        });
                    }
                    break;
                case 'dev_name':
                    if (data[i].ALLKGL && data[i].ALLKGL.length) {
                        this.viewEcharsList.push({
                            id: i,
                            text: data[i].ALLKGL[0].DEV_PRO
                        });
                    } else {
                        this.viewEcharsList.push({
                            id: i,
                            text: data[i].DEV_NAME + DEV_PRO + DEV_TYPE
                        });
                    }
                    break;
            }
        }
        this.getViewWindow(data, name);
    }
    getViewWindow(data, name) {
        if (this.viewEcharsList.length > 1) {
            this.viewChild2(data, name);
        }
        if (this.viewEcharsList.length > 0) {
            this.viewChild1(data, name);
        }
    }
    getViewFullscreen(data, name) {
        if (this.viewEcharsList.length > 3) {
            this.viewChild14(data, name);
        }
        if (this.viewEcharsList.length > 2) {
            this.viewChild13(data, name);
        }
        if (this.viewEcharsList.length > 1) {
            this.viewChild12(data, name);
        }
        if (this.viewEcharsList.length > 0) {
            this.viewChild11(data, name);
        }
    }

    viewChild1(data, name) {
        setTimeout(() => {
            this.viewStatus1 = true;
            this.viewEcharsValue1 = this.viewEcharsList[0].id;
            this.getEcharts('dqtxEchars1', data[this.viewEcharsValue1], name);
        }, 500);
    }
    viewChild2(data, name) {
        setTimeout(() => {
            this.viewStatus2 = true;
            this.viewEcharsValue2 = this.viewEcharsList[1].id;
            this.getEcharts('dqtxEchars2', data[this.viewEcharsValue2], name);
        }, 500);
    }
    viewChild11(data, name) {
        setTimeout(() => {
            this.viewStatus11 = true;
            this.viewEcharsValue11 = this.viewEcharsList[0].id;
            this.getEcharts('dqtxEchars11', data[this.viewEcharsValue11], name);
        }, 500);
    }
    viewChild12(data, name) {
        setTimeout(() => {
            this.viewStatus12 = true;
            this.viewEcharsValue12 = this.viewEcharsList[1].id;
            this.getEcharts('dqtxEchars12', data[this.viewEcharsValue12], name);
        }, 500);
    }
    viewChild13(data, name) {
        setTimeout(() => {
            this.viewStatus13 = true;
            this.viewEcharsValue13 = this.viewEcharsList[2].id;
            this.getEcharts('dqtxEchars13', data[this.viewEcharsValue13], name);
        }, 500);
    }
    viewChild14(data, name) {
        setTimeout(() => {
            this.viewStatus14 = true;
            this.viewEcharsValue14 = this.viewEcharsList[3].id;
            this.getEcharts('dqtxEchars14', data[this.viewEcharsValue14], name);
        }, 500);
    }

    viewEcharsChange(e, id) {
        this.getEcharts(id, this.viewEcharsData[e], this.viewEcharsName);
    }

    getEcharts(id, data, type) {
        this.yzkdType = '';
        const value = [];
        let formatdata: any = [];
        let name = [];
        let time = [];
        let DEV_PRO = data.DEV_PRO;
        let DEV_TYPE = data.DEV_TYPE;

        switch (id) {
            case 'dqtxEchars1': this.kglTableStatus1 = false; this.viewStatus1 = true; break;
            case 'dqtxEchars2': this.kglTableStatus2 = false; this.viewStatus2 = true; break;
            case 'dqtxEchars11': this.kglTableStatus11 = false; this.viewStatus11 = true; break;
            case 'dqtxEchars12': this.kglTableStatus12 = false; this.viewStatus12 = true; break;
            case 'dqtxEchars13': this.kglTableStatus13 = false; this.viewStatus13 = true; break;
            case 'dqtxEchars14': this.kglTableStatus14 = false; this.viewStatus14 = true; break;
        }
        if (!DEV_PRO) {
            DEV_PRO = '';
        }
        if (!DEV_TYPE) {
            DEV_TYPE = '';
        }
        if (data.VALUE && data.VALUE.XVALUE) {
            if (data.VALUE.VALUEG) {
                // 功率
                formatdata.push({ name: '功率', smooth: true, type: 'line', data: data.VALUE.VALUEG });
                name.push('功率');
            } else {
                // 同轴曲线
                if (data.VALUE.VALUEA.length) {
                    formatdata.push({ name: 'A相曲线', smooth: true, type: 'line', data: data.VALUE.VALUEA });
                    name.push('A相曲线');
                }
                if (data.VALUE.VALUEB.length) {
                    formatdata.push({ name: 'B相曲线', smooth: true, type: 'line', data: data.VALUE.VALUEB });
                    name.push('B相曲线');
                }
                if (data.VALUE.VALUEC.length) {
                    formatdata.push({ name: 'C相曲线', smooth: true, type: 'line', data: data.VALUE.VALUEC });
                    name.push('C相曲线');
                }
            }
            time = data.VALUE.XVALUE;
            this.getSeries(id, name, time, formatdata);
        } else {
            const kglcolor = '#03cc5d';
            if (data.ALLKGL) {
                // 开关量或其他
                switch (id) {
                    case 'dqtxEchars1': this.kglTableStatus1 = true; this.viewStatus1 = true; break;
                    case 'dqtxEchars2': this.kglTableStatus2 = true; this.viewStatus2 = true; break;
                    case 'dqtxEchars11': this.kglTableStatus11 = true; this.viewStatus11 = true; break;
                    case 'dqtxEchars12': this.kglTableStatus12 = true; this.viewStatus12 = true; break;
                    case 'dqtxEchars13': this.kglTableStatus13 = true; this.viewStatus13 = true; break;
                    case 'dqtxEchars14': this.kglTableStatus14 = true; this.viewStatus14 = true; break;
                }
                this.yzkdType = 'kgl';
                formatdata = data.ALLKGL;
                // let count = 0;
                // 时间区间补秒
                // for (const item of data.ALLKGL) {
                //     this.supplyTime(item.VALUE[0].devkgl, (stime, svalue) => {
                //         time = stime;
                //         name.push(item.VALUE[0].devname);
                //         this.kglNameList = name;
                //         for (let j = 0; j < svalue.length; j++) {
                //             svalue[j] = svalue[j] + count;
                //         }
                //         formatdata.push({
                //             name: item.VALUE[0].devname,
                //             type: 'line',
                //             step: 'start',
                //             data: svalue
                //         });
                //     });
                //     count += 2;
                // }
            } else {
                for (const list of data.VALUE) {
                    time.push(list.TIME);
                    value.push(Number(list.VALUE));
                }
                name = [];
                formatdata.push({
                    name: type === 'name' ? data.NAME : data.DEV_NAME + '-' + DEV_PRO + '-' + DEV_TYPE,
                    type: 'line',
                    smooth: true,
                    barGap: '-100%',
                    barCategoryGap: '0%',
                    lineStyle: { normal: { color: kglcolor } },
                    itemStyle: { normal: { color: kglcolor } },
                    data: ''
                });
                for (const item of formatdata) {
                    item.data = value;
                }
            }
            this.getSeries(id, name, time, formatdata);
        }
    }
    // 时间区间补秒
    // supplyTime(data, callback) {
    //     const kglDataTime = [];
    //     const kglDataValue = [];
    //     let kglTime = 0;
    //     data.sort(compare('time'));

    //     function compare(property) {
    //         return (a, b) => {
    //             const value1 = a[property];
    //             const value2 = b[property];
    //             return Number(value1) - Number(value2);
    //         };
    //     }
    //     for (let i = 0; i < data.length; i++) {
    //         if (data[i + 1]) {
    //             kglTime = data[i].time;
    //             for (let j = 0; j < data[i + 1].time - data[i].time; j++) {
    //                 kglDataTime.push(this.formatTimeService.formatTime(kglTime * 1000));
    //                 kglDataValue.push(Number(data[i].value));
    //                 kglTime += 1;
    //             }
    //         } else {
    //             kglDataTime.push(this.formatTimeService.formatTime(kglTime * 1000));
    //             kglDataValue.push(Number(data[i].value));
    //         }
    //     }
    //     if (callback) {
    //         callback(kglDataTime, kglDataValue);
    //     }
    // }

    getSeries(id, name, time, formatdata) {
        function compare(property) {
            return (a, b) => {
                const value1 = a[property];
                const value2 = b[property];
                return Number(value1) - Number(value2);
            };
        }
        const yz: any = [{
            type: 'value',
            splitLine: {
                show: true,
                lineStyle: {
                    color: ['#aaa'],
                    width: 1,
                    type: 'solid'
                }
            },
            axisLabel: {
                show: true
            }
        }];
        if (this.yzkdType === 'kgl') {
            this.kglTableList = [];
            for (let i = 0; i < formatdata.length; i++) {
                this.kglTableList.push({
                    children: []
                });
                formatdata[i].VALUE[0].devkgl.sort(compare('time'));
                for (let j = 0; j < formatdata[i].VALUE[0].devkgl.length; j++) {
                    if (i === 0 && j === 0 || j === 0) {
                        this.kglTableList[i].children.push({
                            head: '',
                            body: formatdata[i].VALUE[0].devname
                        });
                    } else {
                        this.kglTableList[i].children.push({
                            head: this.datePipe.transform(formatdata[i].VALUE[0].devkgl[j].time * 1000, 'yyyy-MM-dd HH:mm:ss'),
                            body: Number(formatdata[i].VALUE[0].devkgl[j].value)
                        });
                    }
                }
            }
            formatdata = '';
        }
        setTimeout(() => {
            echarts.init(document.getElementById(id)).setOption({
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        let array = '';
                        for (const item of params) {
                            array += '<p style="font-size:16px">名称：' + item.seriesName + '<br>时间：' + item.name + '<br>';
                            array += '数值：' + item.data;
                            array += '</p>';
                        }
                        return array;
                    }
                },
                legend: {
                    data: name
                },
                grid: {
                    left: '10%',
                    right: '5%',
                    top: '8%',
                    bottom: '8%',
                    containLabel: false
                },
                xAxis: [{
                    type: 'category',
                    axisLabel: {
                        show: false
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: ['#aaa'],
                            width: 1,
                            type: 'solid'
                        }
                    },
                    data: time
                }],
                yAxis: yz,
                series: formatdata
            }, true);
        }, 500);
    }
}
